package com.iuweb.login.realm;

import com.iuweb.login.model.User;
import com.iuweb.login.service.LoginService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ruiwu
 * @version V1.0
 * @Description: Shiro自定义域
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;

    /**
     * 用于的权限的认证。
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = principalCollection.getPrimaryPrincipal().toString() ;
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo() ;
        //Set<String> roleName = userService.findRoles(username) ;
        //Set<String> permissions = userService.findPermissions(username) ;
        //info.setRoles(roleName);
        //info.setStringPermissions(permissions);
        return info;
    }
    /**
     * 首先执行这个登录验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        //获取用户账号
        String username = (String) token.getPrincipal();
        User user = loginService.findUserByUsername(username) ;
        if(user.getUserName().equals(username)){
            return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());
        }else{
            throw new AuthenticationException();
        }
    }
}